/*
  +----------------------------------------------------------------------+
  | PHP Version 7                                                        |
  +----------------------------------------------------------------------+
  | Copyright (c) 1997-2017 The PHP Group                                |
  +----------------------------------------------------------------------+
  | This source file is subject to version 3.01 of the PHP license,      |
  | that is bundled with this package in the file LICENSE, and is        |
  | available through the world-wide-web at the following url:           |
  | http://www.php.net/license/3_01.txt                                  |
  | If you did not receive a copy of the PHP license and are unable to   |
  | obtain it through the world-wide-web, please send a note to          |
  | license@php.net so we can mail you a copy immediately.               |
  +----------------------------------------------------------------------+
  | Author:                                                              |
  +----------------------------------------------------------------------+
*/

/* $Id$ */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "php.h"
#include "php_ini.h"
#include "Zend/zend_exceptions.h"
#include "ext/standard/info.h"
#include "ext/standard/php_string.h"
#include "php_ssdb.h"
#include "ext/json/php_json.h"

/* If you declare any globals in php_ssdb.h uncomment this:
ZEND_DECLARE_MODULE_GLOBALS(ssdb)
*/

/* True global resources - no need for thread safety here */
static zend_class_entry* ssdb_class_entry;
static zend_class_entry* ssdbexception_class_entry;
static zend_class_entry* ssdbtimeoutexception_class_entry;
static zend_class_entry* simplessdb_class_entry;
static zend_class_entry* ssdb_response_class_entry;

#define PHP_SSDB_CLASSNAME "SSDB"
#define PHP_SSDB_EXCEPTION_CLASSNAME "SSDBException"
#define PHP_SSDB_TIMEOUT_EXCEPTION_CLASSNAME "SSDBTimeoutException"
#define PHP_SIMPLE_SSDB_CLASSNAME "SimpleSSDB"
#define PHP_SSDB_RESPONSE_CLASSNAME "SSDB_Response"

PHP_MINIT_FUNCTION(ssdb);
PHP_MSHUTDOWN_FUNCTION(ssdb);
PHP_MINFO_FUNCTION(ssdb);

/* SimpleSSDB Functions */
PHP_METHOD(SimpleSSDB, __construct);

/* SSDB_Response Functions */
PHP_METHOD(SSDB_Response, __construct);
PHP_METHOD(SSDB_Response, __toString);
PHP_METHOD(SSDB_Response, ok);
PHP_METHOD(SSDB_Response, not_found);

/* SimpleSSDB Functions */
PHP_METHOD(SSDB, __construct);
PHP_METHOD(SSDB, set_timeout);
PHP_METHOD(SSDB, easy);
PHP_METHOD(SSDB, close);
PHP_METHOD(SSDB, closed);
PHP_METHOD(SSDB, batch);
PHP_METHOD(SSDB, multi);
PHP_METHOD(SSDB, exec);
PHP_METHOD(SSDB, request);
PHP_METHOD(SSDB, auth);
PHP_METHOD(SSDB, __call);
PHP_METHOD(SSDB, check_seay_resp);
PHP_METHOD(SSDB, multi_set);
PHP_METHOD(SSDB, multi_hset);
PHP_METHOD(SSDB, multi_zset);
PHP_METHOD(SSDB, incr);
PHP_METHOD(SSDB, decr);
PHP_METHOD(SSDB, zincr);
PHP_METHOD(SSDB, zdecr);
PHP_METHOD(SSDB, zadd);
PHP_METHOD(SSDB, zRevRank);
PHP_METHOD(SSDB, zRevRange);
PHP_METHOD(SSDB, hincr);
PHP_METHOD(SSDB, hdecr);
PHP_METHOD(SSDB, send_req);
PHP_METHOD(SSDB, recv_resp);
PHP_METHOD(SSDB, send);
PHP_METHOD(SSDB, recv);
PHP_METHOD(SSDB, parse);

#define SSDB_CTOR(class_name, func_name, arginfo, flags) PHP_ME(class_name, func_name, arginfo, flags)

/* {{{ arginfo */
ZEND_BEGIN_ARG_INFO(arginfo_soap__void, 0)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_simplessdb___construct, 0, 0, 2)
	ZEND_ARG_INFO(0, host)
	ZEND_ARG_INFO(0, port)
	ZEND_ARG_INFO(0, timeout_ms)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_ssdb___call, 0, 0, 2)
	ZEND_ARG_INFO(0, function_name)
	ZEND_ARG_INFO(0, arguments)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arg_info_ssdb_auth, 0, 0, 1)
	ZEND_ARG_INFO(0, password)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arg_info_ssdb_send, 0, 0, 1)
	ZEND_ARG_ARRAY_INFO(0, data, 1)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_ssdb_response___construct, 0, 0, 0)
	ZEND_ARG_INFO(0, code)
	ZEND_ARG_INFO(0, data_or_message)
ZEND_END_ARG_INFO()

/* }}} */

static const zend_function_entry ssdb_methods[] = {
	SSDB_CTOR(SSDB, __construct, NULL, ZEND_ACC_PUBLIC | ZEND_ACC_CTOR)
	PHP_ME(SSDB, set_timeout, NULL, ZEND_ACC_PUBLIC)
	PHP_ME(SSDB, easy, NULL, ZEND_ACC_PUBLIC)
	PHP_ME(SSDB, close, NULL, ZEND_ACC_PUBLIC)
	PHP_ME(SSDB, closed, NULL, ZEND_ACC_PUBLIC)
	PHP_ME(SSDB, batch, NULL, ZEND_ACC_PUBLIC)
	PHP_ME(SSDB, multi, NULL, ZEND_ACC_PUBLIC)
	PHP_ME(SSDB, exec, NULL, ZEND_ACC_PUBLIC)
	PHP_ME(SSDB, request, NULL, ZEND_ACC_PUBLIC)
	PHP_ME(SSDB, auth, arg_info_ssdb_auth, ZEND_ACC_PUBLIC)
	PHP_ME(SSDB, __call, arginfo_ssdb___call, ZEND_ACC_PUBLIC)
	PHP_ME(SSDB, check_seay_resp, NULL, ZEND_ACC_PUBLIC)
	PHP_ME(SSDB, multi_set, NULL, ZEND_ACC_PUBLIC)
	PHP_ME(SSDB, multi_hset, NULL, ZEND_ACC_PUBLIC)
	PHP_ME(SSDB, multi_zset, NULL, ZEND_ACC_PUBLIC)
	PHP_ME(SSDB, incr, NULL, ZEND_ACC_PUBLIC)
	PHP_ME(SSDB, decr, NULL, ZEND_ACC_PUBLIC)
	PHP_ME(SSDB, zincr, NULL, ZEND_ACC_PUBLIC)
	PHP_ME(SSDB, zdecr, NULL, ZEND_ACC_PUBLIC)
	PHP_ME(SSDB, zadd, NULL, ZEND_ACC_PUBLIC)
	PHP_ME(SSDB, zRevRank, NULL, ZEND_ACC_PUBLIC)
	PHP_ME(SSDB, zRevRange, NULL, ZEND_ACC_PUBLIC)
	PHP_ME(SSDB, hincr, NULL, ZEND_ACC_PUBLIC)
	PHP_ME(SSDB, hdecr, NULL, ZEND_ACC_PUBLIC)
	PHP_ME(SSDB, send_req, NULL, ZEND_ACC_PUBLIC)
	PHP_ME(SSDB, recv_resp, NULL, ZEND_ACC_PUBLIC)
	PHP_ME(SSDB, send, arg_info_ssdb_send, ZEND_ACC_PUBLIC)
	PHP_ME(SSDB, recv, NULL, ZEND_ACC_PUBLIC)
	PHP_ME(SSDB, parse, NULL, ZEND_ACC_PUBLIC)
	PHP_FE_END
};
static const zend_function_entry ssdb_response_methods[] = {
	SSDB_CTOR(SSDB_Response, __construct, arginfo_ssdb_response___construct, ZEND_ACC_PUBLIC | ZEND_ACC_CTOR)
	PHP_ME(SSDB_Response, __toString, NULL, ZEND_ACC_PUBLIC)
	PHP_ME(SSDB_Response, ok, NULL, ZEND_ACC_PUBLIC)
	PHP_ME(SSDB_Response, not_found, NULL, ZEND_ACC_PUBLIC)
	PHP_FE_END
};
static const zend_function_entry simple_ssdb_methods[] = {
	SSDB_CTOR(SimpleSSDB, __construct, arginfo_simplessdb___construct, ZEND_ACC_PUBLIC | ZEND_ACC_CTOR)
	PHP_FE_END
};

/* {{{ PHP_INI
 */
/* Remove comments and fill if you need to have entries in php.ini
PHP_INI_BEGIN()
    STD_PHP_INI_ENTRY("ssdb.global_value",      "42", PHP_INI_ALL, OnUpdateLong, global_value, zend_ssdb_globals, ssdb_globals)
    STD_PHP_INI_ENTRY("ssdb.global_string", "foobar", PHP_INI_ALL, OnUpdateString, global_string, zend_ssdb_globals, ssdb_globals)
PHP_INI_END()
*/
/* }}} */

/* Remove the following function when you have successfully modified config.m4
   so that your module can be compiled into PHP, it exists only for testing
   purposes. */

/* Every user-visible function in PHP should document itself in the source */
/* {{{ proto string confirm_ssdb_compiled(string arg)
   Return a string to confirm that the module is compiled in */
PHP_FUNCTION(confirm_ssdb_compiled)
{
	char *arg = NULL;
	size_t arg_len;
	zend_string *strg;

	if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &arg, &arg_len) == FAILURE) {
		return;
	}

	strg = strpprintf(0, "Congratulations! You have successfully modified ext/%.78s/config.m4. Module %.78s is now compiled into PHP.", "ssdb", arg);

	RETURN_STR(strg);
}
/* }}} */
/* The previous line is meant for vim and emacs, so it can correctly fold and
   unfold functions in source code. See the corresponding marks just before
   function definition, where the functions purpose is also documented. Please
   follow this convention for the convenience of others editing your code.
*/

/* {{{
PHP_FUNCTION()
{
	if (zend_parse_parameters_none() == FAILURE) {
		return;
	}
	php_error(E_WARNING, ": not yet implemented");
}
}}} */


/* {{{ php_ssdb_init_globals
 */
/* Uncomment this function if you have INI entries
static void php_ssdb_init_globals(zend_ssdb_globals *ssdb_globals)
{
	ssdb_globals->global_value = 0;
	ssdb_globals->global_string = NULL;
}
*/
/* }}} */

/* {{{ PHP_MINIT_FUNCTION
 */
PHP_MINIT_FUNCTION(ssdb)
{
	zend_class_entry ce;

	/* Register SSDB class */
	INIT_CLASS_ENTRY(ce, PHP_SSDB_CLASSNAME, ssdb_methods);
	ssdb_class_entry = zend_register_internal_class(&ce);

	zend_declare_property_bool(ssdb_class_entry, "debug", sizeof("debug")-1, 0, ZEND_ACC_PRIVATE);
	zend_declare_property_null(ssdb_class_entry, "sock", sizeof("sock")-1, ZEND_ACC_PUBLIC);
	zend_declare_property_bool(ssdb_class_entry, "_closed", sizeof("_closed")-1, 0, ZEND_ACC_PRIVATE);
	zend_declare_property_string(ssdb_class_entry, "recv_buf", sizeof("recv_buf")-1, "", ZEND_ACC_PRIVATE);
	zend_declare_property_bool(ssdb_class_entry, "_easy", sizeof("_easy")-1, 0, ZEND_ACC_PRIVATE);
	zend_declare_property_null(ssdb_class_entry, "last_resp", sizeof("last_resp")-1, ZEND_ACC_PUBLIC);
	zend_declare_property_null(ssdb_class_entry, "async_auth_password", sizeof("async_auth_password")-1, ZEND_ACC_PRIVATE);
	zend_declare_property_bool(ssdb_class_entry, "batch_mode", sizeof("batch_mode")-1, 0, ZEND_ACC_PRIVATE);

	/* Register SSDBException class */
	INIT_CLASS_ENTRY(ce, PHP_SSDB_EXCEPTION_CLASSNAME, NULL);
	ssdbexception_class_entry = zend_register_internal_class_ex(&ce, zend_ce_exception);

	/* Register SSDB_Response class */
	INIT_CLASS_ENTRY(ce, PHP_SSDB_RESPONSE_CLASSNAME, ssdb_response_methods);
	ssdb_response_class_entry = zend_register_internal_class(&ce);

	zend_declare_property_null(ssdb_response_class_entry, "cmd", sizeof("cmd")-1, ZEND_ACC_PUBLIC);
	zend_declare_property_null(ssdb_response_class_entry, "code", sizeof("code")-1, ZEND_ACC_PUBLIC);
	zend_declare_property_null(ssdb_response_class_entry, "data", sizeof("data")-1, ZEND_ACC_PUBLIC);
	zend_declare_property_null(ssdb_response_class_entry, "message", sizeof("message")-1, ZEND_ACC_PUBLIC);

	/* Register SSDBTimeoutException class */
	INIT_CLASS_ENTRY(ce, PHP_SSDB_TIMEOUT_EXCEPTION_CLASSNAME, NULL);
	ssdbtimeoutexception_class_entry = zend_register_internal_class_ex(&ce, ssdbexception_class_entry);

	/* Register SimpleSSDB class */
	INIT_CLASS_ENTRY(ce, PHP_SIMPLE_SSDB_CLASSNAME, simple_ssdb_methods);
	simplessdb_class_entry = zend_register_internal_class_ex(&ce, ssdb_class_entry);


	// le_sdl = zend_register_list_destructors_ex(delete_sdl_res, NULL, "SOAP SDL", module_number);
	// le_url = zend_register_list_destructors_ex(delete_url_res, NULL, "SOAP URL", module_number);
	// le_service = zend_register_list_destructors_ex(delete_service_res, NULL, "SOAP service", module_number);
	// le_typemap = zend_register_list_destructors_ex(delete_hashtable_res, NULL, "SOAP table", module_number);

	// REGISTER_LONG_CONSTANT("SOAP_1_1", SOAP_1_1, CONST_CS | CONST_PERSISTENT);
	// REGISTER_LONG_CONSTANT("SOAP_1_2", SOAP_1_2, CONST_CS | CONST_PERSISTENT);

	// REGISTER_LONG_CONSTANT("SOAP_PERSISTENCE_SESSION", SOAP_PERSISTENCE_SESSION, CONST_CS | CONST_PERSISTENT);
	// REGISTER_LONG_CONSTANT("SOAP_PERSISTENCE_REQUEST", SOAP_PERSISTENCE_REQUEST, CONST_CS | CONST_PERSISTENT);
	// REGISTER_LONG_CONSTANT("SOAP_FUNCTIONS_ALL", SOAP_FUNCTIONS_ALL, CONST_CS | CONST_PERSISTENT);
	// old_error_handler = zend_error_cb;
	// zend_error_cb = soap_error_handler;

	/* If you have INI entries, uncomment these lines
	REGISTER_INI_ENTRIES();
	*/
	return SUCCESS;
}
/* }}} */

/* {{{ PHP_MSHUTDOWN_FUNCTION
 */
PHP_MSHUTDOWN_FUNCTION(ssdb)
{
	/* uncomment this line if you have INI entries
	UNREGISTER_INI_ENTRIES();
	*/
	return SUCCESS;
}
/* }}} */

/* Remove if there's nothing to do at request start */
/* {{{ PHP_RINIT_FUNCTION
 */
PHP_RINIT_FUNCTION(ssdb)
{
#if defined(COMPILE_DL_SSDB) && defined(ZTS)
	ZEND_TSRMLS_CACHE_UPDATE();
#endif
	return SUCCESS;
}
/* }}} */

/* Remove if there's nothing to do at request end */
/* {{{ PHP_RSHUTDOWN_FUNCTION
 */
PHP_RSHUTDOWN_FUNCTION(ssdb)
{
	return SUCCESS;
}
/* }}} */

/* {{{ PHP_MINFO_FUNCTION
 */
PHP_MINFO_FUNCTION(ssdb)
{
	php_info_print_table_start();
	php_info_print_table_header(2, "ssdb support", "enabled");
	php_info_print_table_end();

	/* Remove comments if you have entries in php.ini
	DISPLAY_INI_ENTRIES();
	*/
}
/* }}} */

/* {{{ ssdb_functions[]
 *
 * Every user visible function must have an entry in ssdb_functions[].
 */
const zend_function_entry ssdb_functions[] = {
	PHP_FE(confirm_ssdb_compiled,	NULL)		/* For testing, remove later. */
	PHP_FE_END	/* Must be the last line in ssdb_functions[] */
};
/* }}} */

/* {{{ ssdb_module_entry
 */
zend_module_entry ssdb_module_entry = {
	STANDARD_MODULE_HEADER,
	"ssdb",
	ssdb_functions,
	PHP_MINIT(ssdb),
	PHP_MSHUTDOWN(ssdb),
	NULL, NULL, 
	PHP_MINFO(ssdb),
	PHP_SSDB_VERSION,
	STANDARD_MODULE_PROPERTIES
};
/* }}} */

#ifdef COMPILE_DL_SSDB
#ifdef ZTS
ZEND_TSRMLS_CACHE_DEFINE()
#endif
ZEND_GET_MODULE(ssdb)
#endif


/* SimpleSSDB Functions */
PHP_METHOD(SimpleSSDB, __construct)
{
	char *host;
	size_t host_len;
	zend_long port, timeout_ms=2000;
	zval retval;
	zval tmp_obj;
	zval argv[3];
	zval fname;

	if (zend_parse_parameters(ZEND_NUM_ARGS(), "sl|l", &host, &host_len, &port, &timeout_ms) == FAILURE) {
		return;
	}
	
	object_init_ex(&tmp_obj, ssdb_class_entry);

	ZVAL_STRINGL(&argv[0], host, host_len);
	ZVAL_LONG(&argv[1], port);
	ZVAL_LONG(&argv[2], timeout_ms);

	ZVAL_STRING(&fname, ZEND_CONSTRUCTOR_FUNC_NAME);

	if (call_user_function(EG(function_table), &tmp_obj, &fname, &retval, 3, argv) == FAILURE) {
		php_error_docref(NULL, E_ERROR, "Error calling SSDB constructor");
	}

	if (EG(exception)) {
		php_output_discard();

		zend_throw_exception_ex(NULL, 0, "Failed calling %s::__construct()", ZSTR_VAL(ssdb_class_entry->name));

		zval_ptr_dtor(&retval);
		zval_ptr_dtor(&fname);
		zval_ptr_dtor(&tmp_obj);

		zval_ptr_dtor(&argv[0]);
		zval_ptr_dtor(&argv[1]);
		zval_ptr_dtor(&argv[2]);

		return;
	}

	zval_ptr_dtor(&argv[0]);
	zval_ptr_dtor(&argv[1]);
	zval_ptr_dtor(&argv[2]);

	zval_ptr_dtor(&tmp_obj);
	zval_ptr_dtor(&fname);
	ZVAL_NULL(&retval);
	// zval_ptr_dtor(&fname);
	// zval_ptr_dtor(&retval);
	// zval_ptr_dtor(&tmp_obj);

	object_init_ex(&tmp_obj, simplessdb_class_entry);

	ZVAL_STRING(&fname, "easy");

	if (call_user_function(EG(function_table), &tmp_obj, &fname, &retval, 0, NULL) == FAILURE) {
		php_error_docref(NULL, E_ERROR, "Error calling SimpleSSDB easy");
	}

	zval_ptr_dtor(&fname);
	zval_ptr_dtor(&retval);
	zval_ptr_dtor(&tmp_obj);

	/* Call constructor */
	// if (zend_hash_str_exists(&Z_OBJCE(tmp_ssdb)->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1)) {

	// 	zval_ptr_dtor(&tmp_ssdb);

	// 	strg = strpprintf(0, "ssdb __construct");
	// 	RETURN_STR(strg);
	// }
	// 	zval c_ret, constructor;

	// 	ZVAL_STRINGL(&argv[0], host, host_len);
	// 	ZVAL_LONG(&argv[1], port);
	// 	ZVAL_LONG(&argv[2], timeout_ms);

	// 	ZVAL_STRING(&constructor, ZEND_CONSTRUCTOR_FUNC_NAME);
	// 	if (call_user_function(NULL, &tmp_ssdb, &constructor, &c_ret, 3, argv) == FAILURE) {
	// 		php_error_docref(NULL, E_ERROR, "Error calling SSDB constructor");
	// 	}
	// 	if (EG(exception)) {
	// 		php_output_discard();
	// 		// _soap_server_exception(service, function, getThis());

	// 		zval_ptr_dtor(&argv[0]);
	// 		zval_ptr_dtor(&argv[1]);
	// 		zval_ptr_dtor(&argv[2]);

	// 		zval_dtor(&constructor);
	// 		zval_dtor(&c_ret);
	// 		zval_ptr_dtor(&tmp_ssdb);
	// 		// goto fail;
	// 	}

	// 	zval_ptr_dtor(&argv[0]);
	// 	zval_ptr_dtor(&argv[1]);
	// 	zval_ptr_dtor(&argv[2]);

	// 	zval_dtor(&constructor);
	// 	zval_dtor(&c_ret);
	// 	zval_ptr_dtor(&tmp_ssdb);
	// }

	// object_init_ex(object_name, ssdb_class_entry);
	// ZVAL_STRING(&function_name, "easy");
	// if (call_user_function(EG(function_table), object_name, &function_name, &retval, 0, NULL) == FAILURE) {
	// 	php_error_docref(NULL, E_WARNING, "Could not call easy");
	// }

	// zval_ptr_dtor(&retval);
}

/* SSDB_Response Functions */
PHP_METHOD(SSDB_Response, __construct)
{
	char *code = NULL;
	size_t code_len;
	zval *self;
	zend_string *data_or_message = NULL;

	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|sS!", &code, &code_len, data_or_message) == FAILURE) {
		return;
	}

	self = getThis();

	if (code == NULL) {
		code = (char *) malloc(sizeof(char) * 2);

		sprintf(code, "ok");

		code_len = strlen("ok");
	}

	zend_update_property_stringl(ssdb_response_class_entry, self, "code", sizeof("code") - 1, code, code_len);

	if (strcmp(code, "ok") == 0) {
		if (data_or_message == NULL) {
			zend_update_property_null(ssdb_response_class_entry, self, "data", sizeof("data") - 1);
		} else {
			zend_update_property_string(ssdb_response_class_entry, self, "data", sizeof("data") - 1, ZSTR_VAL(data_or_message));
		}
	} else {
		if (data_or_message == NULL) {
			zend_update_property_null(ssdb_response_class_entry, self, "message", sizeof("message") - 1);
		} else {
			zend_update_property_string(ssdb_response_class_entry, self, "message", sizeof("message") - 1, ZSTR_VAL(data_or_message));
		}
		
	}

	if (data_or_message != NULL) {
		zend_string_release(data_or_message);		
	}
}
PHP_METHOD(SSDB_Response, __toString)
{
	zval *code, *res, *cmd, rv;

	zend_string *s, *result;

	smart_str buf = {0};

	code = zend_read_property(ssdb_response_class_entry, getThis(), "code", sizeof("code") - 1, 1, &rv);

	if (strcmp(Z_STRVAL_P(code), "ok") == 0) {
		res = zend_read_property(ssdb_response_class_entry, getThis(), "data", sizeof("data") - 1, 1, &rv);
		if (Z_TYPE_P(res) == IS_NULL) {
			s = zend_string_init("", strlen(""), 0);
		} else {
			php_json_encode(&buf, res, 0);

			s = buf.s;
			// s = zend_string_init("json_encode", strlen("json_encode"), 0); //json_encode(res);
		}
	} else {
		res = zend_read_property(ssdb_response_class_entry, getThis(), "message", sizeof("message") - 1, 1, &rv);
		s = Z_STR_P(res);
	}

	cmd = zend_read_property(ssdb_response_class_entry, getThis(), "cmd", sizeof("cmd") - 1, 1, &rv);

	if (Z_TYPE_P(cmd) == IS_NULL) {
		result = strpprintf(0, "%-13s %12s %s", "", Z_STRVAL_P(code), ZSTR_VAL(s));
	} else {
		result = strpprintf(0, "%-13s %12s %s", Z_STRVAL_P(cmd), Z_STRVAL_P(code), ZSTR_VAL(s));		
	}

	zend_string_release(s);

	RETURN_STR(result);

	zend_string_release(result);
}
PHP_METHOD(SSDB_Response, ok)
{
	zval *code, rv;

	code = zend_read_property(ssdb_response_class_entry, getThis(), "code", sizeof("code") - 1, 1, &rv);

	if (strcmp(Z_STRVAL_P(code), "ok") == 0) {
		RETURN_TRUE;
	}
	
	RETURN_FALSE;
}
PHP_METHOD(SSDB_Response, not_found)
{
	zval *code, rv;

	code = zend_read_property(ssdb_response_class_entry, getThis(), "code", sizeof("code") - 1, 1, &rv);

	if (strcmp(Z_STRVAL_P(code), "not_found") == 0) {
		RETURN_TRUE;
	}
	
	RETURN_FALSE;
}

/* SimpleSSDB Functions */
PHP_METHOD(SSDB, __construct)
{
	zval *z_host;
	zend_long port, timeout_ms;

	php_stream *stream = NULL;
	php_timeout_ull conv;
	struct timeval tv;
	char *hashkey = NULL;
	// zend_long flags = STREAM_XPORT_BIND | STREAM_XPORT_LISTEN;
	int err;
	zend_long flags = STREAM_XPORT_CLIENT | STREAM_XPORT_CONNECT;
	zend_string *errstr = NULL;
	php_stream_context *context = NULL;
	char *name;
	size_t namelen;
	zval z_stream;

	// zval str;

	if (zend_parse_parameters(ZEND_NUM_ARGS(), "zl|l", &z_host, &port, &timeout_ms) == FAILURE) {
		return;
	}

	namelen = spprintf(&name, 0, "%s:%d", Z_STRVAL_P(z_host), port);
	
	// spprintf(&hashkey, 0, "ssdb_socket_client__%s", Z_STRVAL_P(z_host));
	spprintf(&hashkey, 0, "ssdb_socket_client");

	conv = (php_timeout_ull) (timeout_ms * 1000.0);
	tv.tv_sec = conv / 1000000;
	tv.tv_usec = conv % 1000000;

	stream = php_stream_xport_create(name, namelen, REPORT_ERRORS, (int) flags, hashkey, &tv, context, &errstr, &err);

	if (stream == NULL) {
		zend_string *quoted_host = php_addslashes(Z_STR_P(z_host), 0);

		php_error_docref(NULL, E_WARNING, "unable to connect to %s (%s)", ZSTR_VAL(quoted_host), errstr == NULL ? "Unknown error" : ZSTR_VAL(errstr));

		zend_string_release(quoted_host);
	}

	if (name) {
		efree(name);
	}

	if (hashkey) {
		efree(hashkey);
	}

	if (stream == NULL)	{
		zend_string_release(errstr);

		RETURN_FALSE;
	}

	php_stream_set_chunk_size(stream, 1048576);
	
	php_stream_to_zval(stream, &z_stream);
	stream = NULL;

	zend_update_property(ssdb_class_entry, getThis(), "sock", sizeof("sock") - 1, &z_stream);
	
	// zend_throw_exception_object(&ex);
	zval_ptr_dtor(z_host);
	zval_ptr_dtor(&z_stream);

	zval myarray;
    array_init(&myarray);
	zend_declare_property(ssdb_class_entry, "batch_cmds", sizeof("batch_cmds")-1, &myarray, ZEND_ACC_PRIVATE);
	
	// ZVAL_STRINGL(&str, host, host_len);
	// php_printf("SSDB::__construct host:%s, port: %d, timeout_ms:%d", host, port, timeout_ms);

}
PHP_METHOD(SSDB, set_timeout)
{

}
PHP_METHOD(SSDB, easy)
{
	zend_update_property_bool(ssdb_class_entry, getThis(), "_easy", sizeof("_easy") - 1, 1);

	RETURN_TRUE;
}
PHP_METHOD(SSDB, close)
{
	zval *z_closed;
	zval rv;
	php_stream   *stream = NULL;

	z_closed = zend_read_property(ssdb_class_entry, getThis(), "_closed", sizeof("_closed") - 1, 1, &rv);

	if (Z_TYPE_P(z_closed) == IS_FALSE) {
		php_stream_from_persistent_id("ssdb_socket_client", &stream);
		php_stream_close(stream);
		stream = NULL;

		zend_update_property_bool(ssdb_class_entry, getThis(), "_closedsock", sizeof("_closed") - 1, 1);
		zend_update_property_null(ssdb_class_entry, getThis(), "sock", sizeof("sock") - 1);
	}

	RETURN_TRUE;
}
PHP_METHOD(SSDB, closed)
{
	zval *z_closed, rv;

	z_closed = zend_read_property(ssdb_class_entry, getThis(), "_closed", sizeof("_closed") - 1, 0, &rv);

	if (Z_TYPE_P(z_closed) == IS_TRUE) {
		RETURN_TRUE;
	} else {
		RETURN_FALSE;
	}
}
PHP_METHOD(SSDB, batch)
{
	
}
PHP_METHOD(SSDB, multi)
{
	
}
PHP_METHOD(SSDB, exec)
{
	
}
PHP_METHOD(SSDB, request)
{
	
}
PHP_METHOD(SSDB, auth)
{
	char *password;
	size_t password_len;

	if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &password, &password_len) == FAILURE) {
		return;
	}

	zend_update_property_stringl(ssdb_class_entry, getThis(), "async_auth_password", sizeof("async_auth_password") - 1, password, password_len);

	RETURN_NULL();
}
PHP_METHOD(SSDB, __call)
{
	char *function;
	size_t function_len;
	zval *args;
	zval *real_args = NULL;
	zval *param;
	int arg_count;
	zval rv;
	zval * aap_val;
	zval argv[2];
	zval *z_batch_mode;
	zval *z_batch_cmds;

	HashTable *ht_batch_cmds;

	if (zend_parse_parameters(ZEND_NUM_ARGS(), "sa", &function, &function_len, args) == FAILURE) {
		return;
	}

	char *lower_function = php_strtolower(function, function_len);

	aap_val = zend_read_property(ssdb_class_entry, getThis(), "async_auth_password", sizeof("async_auth_password") - 1, 1, &rv);

	if (Z_TYPE_P(aap_val) != IS_NULL) {
			// $pass = $this->async_auth_password;
			// $this->async_auth_password = null;
			// $auth = $this->__call('auth', array($pass));
			// if($auth !== true){
			// 	throw new Exception("Authentication failed");
			// }
		zval tmp;

		zval fname;
		HashTable *dst;

		zval *dest_elem;

		zval tmp_obj;

		ZVAL_COPY(&tmp, aap_val);

		zend_update_property_null(ssdb_class_entry, getThis(), "async_auth_password", sizeof("async_auth_password") - 1);

		ZVAL_STRING(&fname, "__call");

		ZVAL_STRING(&argv[0], "auth");

		dst = emalloc(sizeof(HashTable));
		zend_hash_init(dst, 1, NULL, ZVAL_PTR_DTOR, 0);

		dest_elem = zend_hash_next_index_insert(dst, &tmp);
		if (dest_elem) {
			zval_add_ref(dest_elem);
		}

		ZVAL_ARR(&argv[1], dst);

		object_init_ex(&tmp_obj, ssdb_class_entry);

		if (call_user_function(EG(function_table), &tmp_obj, &fname, &rv, 2, argv) == FAILURE) {
			php_error_docref(NULL, E_WARNING, "Authentication failed");
			RETURN_FALSE;
		}
	}
	
	z_batch_mode = zend_read_property(ssdb_class_entry, getThis(), "batch_mode", sizeof("batch_mode") - 1, 1, &rv);

	if (Z_TYPE_P(z_batch_mode) == IS_TRUE) {
		// z_batch_cmds = zend_read_property(ssdb_class_entry, getThis(), "batch_cmds", sizeof("batch_cmds") - 1, 1, &rv);
		
		// HashTable *dst;

		// dst = emalloc(sizeof(HashTable));
		// zend_hash_init(dst, 2, NULL, ZVAL_PTR_DTOR, 0);

		// zend_hash_next_index_insert(dst, );

		// zend_hash_next_index_insert(Z_ARRVAL_P(z_batch_cmds), dst);

		ZVAL_OBJ(return_value, Z_OBJ_P(getThis()));
		Z_ADDREF_P(return_value);
		return;
	}

	// arg_count = zend_hash_num_elements(Z_ARRVAL_P(args));
	// if (arg_count > 0) {
	// 	real_args = safe_emalloc(sizeof(zval), arg_count, 0);
	// 	ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(args), param) {
	// 		/*zval_add_ref(param);*/
	// 		ZVAL_DEREF(param);
	// 		ZVAL_COPY_VALUE(&real_args[i], param);
	// 		i++;
	// 	} ZEND_HASH_FOREACH_END();
	// }

	// if (arg_count > 0) {
	// 	efree(real_args);
	// }
}
PHP_METHOD(SSDB, check_seay_resp)
{
	
}
PHP_METHOD(SSDB, multi_set)
{
	
}
PHP_METHOD(SSDB, multi_hset)
{
	
}
PHP_METHOD(SSDB, multi_zset)
{

}
PHP_METHOD(SSDB, incr)
{

}
PHP_METHOD(SSDB, decr) {
	
}
PHP_METHOD(SSDB, zincr)
{

}
PHP_METHOD(SSDB, zdecr)
{
	
}
PHP_METHOD(SSDB, zadd)
{
	
}
PHP_METHOD(SSDB, zRevRank)
{
	
}
PHP_METHOD(SSDB, zRevRange)
{
	
}
PHP_METHOD(SSDB, hincr)
{
	
}
PHP_METHOD(SSDB, hdecr)
{
	
}
PHP_METHOD(SSDB, send_req)
{
	
}
PHP_METHOD(SSDB, recv_resp)
{
	
}
PHP_METHOD(SSDB, send)
{
	zval *data;
	HashTable * ps;
	int nelem;

	zval *param;

	if (zend_parse_parameters(ZEND_NUM_ARGS(), "a!", &data) == FAILURE) {
		return;
	}

	nelem = zend_hash_num_elements(Z_ARRVAL_P(data));

	zend_hash_init(ps, nelem, NULL, ZVAL_PTR_DTOR, 0);

	if (nelem > 0) {
		// real_args = safe_emalloc(sizeof(zval), arg_count, 0);
		ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(data), param) {
			/*zval_add_ref(param);*/
			// ZVAL_DEREF(param);
			// ZVAL_COPY_VALUE(&real_args[i], param);
			zval *p_len;
			ZVAL_LONG(p_len, Z_STRLEN_P(param));

			zend_hash_next_index_insert(ps, p_len);
			zend_hash_next_index_insert(ps, param);
		} ZEND_HASH_FOREACH_END();
	}

	zend_string *delim;

	zval *retv, *rv;
	zval arr;

	zval *debug;

	delim = zend_string_init("\n", strlen("\n"), 0);

	ZVAL_ARR(&arr, ps);

	php_implode(delim, &arr, retv);

	zend_string *s;
	s = strpprintf(0, "%s\n\n", Z_STRVAL_P(retv));

	debug = zend_read_property(ssdb_class_entry, getThis(), "debug", sizeof("debug") - 1, 1, rv);
	if (Z_TYPE_P(debug) == IS_TRUE) {
		RETVAL_STR(s);
		//php_str_replace_common
	}
	zend_string_release(s);
}
PHP_METHOD(SSDB, recv)
{
	
}
PHP_METHOD(SSDB, parse)
{
	
}

/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * End:
 * vim600: noet sw=4 ts=4 fdm=marker
 * vim<600: noet sw=4 ts=4
 */
